<script lang="jsx">
import { openCourtServer } from '@/api/court'
import CRUD from '@/components/CRUD/index.vue'
import CompleteCourt from './components/CompleteCourt.vue'
import CourtSelect from './components/CourtSelect.vue'
import LawyerSelect from './components/LawyerSelect.vue'
import OpenCourtDetail from './components/OpenCourtDetail.vue'
import { ref } from 'vue'
import { useCommonFilter } from '@/hooks/useCommonFilter'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  components: {
    CRUD,
    CompleteCourt,
    CourtSelect,
    LawyerSelect,
  },
  setup() {
    const defendantInfo = (row) => {
      return (
        <div>
          <div>{row.defendant_info?.name}</div>
          <div>{row.defendant_info?.mobile}</div>
          <div>{row.defendant_info?.address}</div>
        </div>
      )
    }
    const arrearsInfo = (row) => {
      return (
        <div>
          <div>总金额：<el-money num={row.countAmount} /></div>
          <div>欠费金额：<el-money num={row.arrears_info?.amount} /></div>
          <div>滞纳金金额：<el-money num={row.arrears_info?.overdue_fine_amount} /></div>
        </div>
      )
    }
    const columns = [
      { label: '编号', prop: 'open_court_record_id', minWidth: '60px', },
      { label: '原告', prop: 'company_info', minWidth: '160px', render: (row) => <span>{row.company_info?.name}<br />{row.community_info?.name}</span> },
      { label: '被告', prop: 'defendant_info', minWidth: '120px', render: defendantInfo },
      { label: '欠费金额', prop: 'arrears_info', minWidth: '200px', render: arrearsInfo },
      { label: '开庭法院', prop: 'court_name', minWidth: '160px', },
      // { label: '开庭律师', prop: 'open_court_user_name' },
      { label: '开庭时间', prop: 'open_datetime', minWidth: '160px' },
      { label: '审级', prop: 'level', minWidth: '80px', },
      { label: '开庭状态', prop: 'openStatus', minWidth: '100px', },
      {
        label: '判决书', prop: 'pj_result_url', minWidth: '100px', render: (row) => {
          return row.pj_result_url && <el-link type="primary"
            href={row.pj_result_url}
            target="_blank"
          >查看判决书</el-link>
        }
      },
    ]
    const { filters } = useCommonFilter([
      'company_id',
      'community_id',
      'open_court_user_id',
      'court_id',
    ])
    const route = useRoute()
    if (route.query.id) {
      filters.push({
        key: 'arrears_data_id',
        value: route.query.id,
      })
    }
    const editForm = [
      {
        label: '法院',
        key: 'court',
        type: 'custom',
        required: true,
        props: { placeholder: '请选择开庭法院', isObject: true },
        render: CourtSelect,
      },
      {
        label: '法庭',
        key: 'court_number',
        type: 'input',
        required: true,
        props: { placeholder: '请输入法庭' },
      },
      {
        label: '审级',
        key: 'level',
        type: 'select',
        required: true,
        options: [
          { label: '一审', value: '一审' },
          { label: '二审', value: '二审' },
          { label: '再审', value: '再审' },
        ],
        props: { placeholder: '请选择审级' },
      },
      {
        label: '开庭时间',
        key: 'open_datetime',
        type: 'datepicker',
        required: true,
        props: { placeholder: '请选择开庭时间', type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
      },
      {
        label: '出庭律师',
        key: 'open_court_user',
        type: 'custom',
        required: true,
        dynamicProps: (form) => {
          return {
            openDatetime: form.open_datetime,
          }
        },
        render: LawyerSelect,
      },
    ]

    const info = ref(null)

    // 完成开庭
    const visible = ref(false)
    const onFinish = (row) => {
      info.value = row
      visible.value = true
    }
    const onClose = () => {
      visible.value = false
    }

    // 查看详情
    const detailVisible = ref(false)
    const onDetail = (row) => {
      detailVisible.value = true
      info.value = row
    }

    //撤销开庭
    const onCancel = async (row) => {
      await ElMessageBox.confirm('是否确认撤销开庭', '提示')
      await openCourtServer.put({
        open_court_id: row.id,
        is_cancel: true
      })
      ElMessage.success('撤销开庭成功')
      getTableData()
    }

    const crudRef = ref(null)
    const getTableData = (keepPage) => {
      // 这里需要传入参数
      crudRef.value.getTableData(keepPage)
    }

    return () => (
      <CRUD
        ref={crudRef}
        title=""
        editText="编辑开庭信息"
        rawKey="open_court_id"
        server={openCourtServer}
        columns={columns}
        filters={filters}
        editForm={editForm}
        editable={(row) => {
          return row.openStatus === '未开庭'
        }}
        fixedColWidth="240px"
        afterGetData={(data) => {
          const now = Date.now()
          data.forEach((item) => {
            item.countAmount = Number((item.arrears_info?.amount + item.arrears_info?.overdue_fine_amount || 0).toFixed(2))
            item.openStatus = new Date(item.open_datetime) > now ? '未开庭' : '已开庭';
            item.open_court_user = {
              user_id: item.open_court_user_id,
              name: item.open_court_user_name,
            }
            item.court = {
              court_id: item.court_id,
              name: item.court_name,
            }
          })
          return data
        }}
        beforeSubmit={(params) => {
          params.court_id = params.court.court_id;
          params.court_name = params.court.name;
          delete params.court
          return params
        }}
        v-slots={{
          handler: ({ row }) => (
            <>
              {row.openStatus === '已开庭' && (
                <el-button type="primary" link onClick={() => onDetail(row)}>
                  详情
                </el-button>
              )}
              {row.openStatus === '已开庭' && !row.is_finished && (
                <el-button type="primary" link onClick={() => onFinish(row)}>
                  完成开庭
                </el-button>
              )}
              {row.openStatus === '未开庭' && !row.is_cancel && (
                <el-button type="primary" link onClick={() => onCancel(row)}>
                  撤销开庭
                </el-button>
              )}
            </>
          ),
          dialog: () => (
            <>
              <el-dialog
                modelValue={visible.value}
                title="完成开庭"
                width="600px"
                onUpdate:modelValue={onClose}
                destroy-on-close
              >
                <CompleteCourt info={info.value} onClose={onClose} onSuccess={() => getTableData(true)} />
              </el-dialog>
              <el-dialog
                modelValue={detailVisible.value}
                title="详情"
                width="600px"
                onUpdate:modelValue={() => detailVisible.value = false}
                destroy-on-close
              >
                <OpenCourtDetail info={info.value} />
              </el-dialog>
            </>
          ),
        }}
      ></CRUD>
    )
  },
}
</script>
